package com.zhouheng.common.exception;

import com.zhouheng.common.entity.ResponseVo;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @RestControllerAdvice
 * 拦截异常，并统一处理
 *
 * @author 周恒
 * @date 20181003 10:24:02
 * @since v1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕捉shiro的异常
     *
     * @param e 描述此参数
     * @return 返回 response bean 描述此返回参数
     * @author 周恒
     * @date 20181003 10:22:45
     * @since v1.0
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResponseVo handle401(ShiroException e) {
        return new ResponseVo(401, e.getMessage());
    }

    /**
     * 捕捉UnauthorizedException
     *
     * @return 返回 response bean 描述此返回参数
     * @author 周恒
     * @date 20181003 10:23:03
     * @since v1.0
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseVo handle401() {
        return new ResponseVo(401, "Unauthorized");
    }

    /**
     * 捕捉其他所有异常
     *
     * @param request 描述此参数
     * @param ex      描述此参数
     * @return 返回 response bean 描述此返回参数
     * @author 周恒
     * @date 20181003 10:23:21
     * @since v1.0
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseVo globalException(HttpServletRequest request, Throwable ex) {
        return new ResponseVo(getStatus(request).value(), ex.getMessage());
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}

